import Vue from 'vue';
import Router from 'vue-router'; // 导入路由
import Login from '../Login'; // 导入其他组件
import Info from '../info'; // 导入其他组件
import Sign from '../Sign'; // 导入其他组件
import YearPeople from '../view/yearPeople'; // 导入其他组件
import YearPeopleManage from '../ManageView/yearPeople/yearPeople';
import ManageInfo from '../ManageInfo';
import YearPeopleAccount from '../ManageView/YearPeopleAccount/yearPeopleAccount';

//------解决重复访问一个界面问题----------
/*
比如账号错误  由于响应拦截器replace与路由首位会多次访问 某一个登录界面
*/
Vue.use(Router);

const RouterPush = Router.prototype.push
Router.prototype.push = function push (to) {
  return RouterPush.call(this, to).catch(err => err)
}
const RouterReplace = Router.prototype.replace
Router.prototype.replace = function replace (to) {
  return RouterReplace.call(this, to).catch(err => err)
}
//-----------------------------------------------
const router = new Router({
  routes: [
    {
      path: '/',
      component: Login,
      beforeEnter: checkRole,
      meta: {
        requiresAuth: true,
      }
    },
    {
      path: '/login',
      component: Login,
      beforeEnter: checkRole,
      meta: {
        requiresAuth: true,
      }
    },
    {
      path: '/sign',
      component: Sign,
      beforeEnter: checkRole,
      meta: {
        requiresAuth: true,
      }
    },
    {
      path: '/info',
      component: Info,
      beforeEnter: checkRole,
      meta: {
        requiresAuth: true,
      },
      children: [
        {
          path: 'yearPeople', // 使用相对路径
          component: YearPeople,
          beforeEnter: checkRole,
          meta: {
            requiresAuth: true,
          }
        }
      ]
    },
    {
      path: '/ManageInfo',
      component: ManageInfo,
      beforeEnter: checkRole,
      meta: {
        requiresAuth: false,
      },
      children: [
        {
          path: 'yearPeopleManage', // 使用相对路径
          component: YearPeopleManage
        },{
          path: 'yearPeopleAccount', // 使用相对路径
          component: YearPeopleAccount
        }
      ]
    }
  ]
});

// 导出路由对象
export default router;

// 全局前置守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login'||to.path === '/sign') {
    // 如果用户访问的是登录页，直接放行
    return next();
  } else {
	  var account = window.sessionStorage.getItem("account");
	  if (account == null) { //用户信息为空,说明用户没有登录
	  	return next("/login");
	  } else {
	  	return next();
	  }
    }
  });

// checkRole 路由守卫函数
const checkRole = (to, from, next) => {
  const Roleuser = sessionStorage.getItem('Roleuser'); // 从本地存储获取用户角色
  if (Roleuser === 'admin') {
    // 管理员角色，允许访问所有页面
    next();
  } else if (Roleuser === 'user') {
    // 普通用户角色，只允许访问特定页面
    if (to.meta.requiresAuth) {
      next(); // 允许访问需要权限的页面
    } else {
      next('/ogin'); // 重定向到未授权页面
    }
  } 
};

